package cn.stylefeng.guns.sys.core.util;

import cn.stylefeng.guns.sys.core.constant.cache.CacheKey;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;
import com.taobao.api.internal.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 钉钉类
 *
 * @author zxd
 * @date 2022/03/08 09:30
 */
@Component
public class DingdingAttendUtil {

    // 应用的appKey
    private static String appKey = "dingvvrsivpeg6bqm4qb";
    // 应用的appSecret
    private static String appSecret = "wly_IoMnP0QXZzaWh-NiSOUxZJgpmDzZeKyy6LPQMktm9iO65RfO14LVYUliokL-";
    // access_token url
    private static String accessTokenUrl = "https://oapi.dingtalk.com/gettoken";
    // 考勤记录 url
    private static String attendanceUrl = "https://oapi.dingtalk.com/attendance/list";

    // 部门 url
    private static String departmentUrl = "https://oapi.dingtalk.com/department/list";
    // 员工 url
    private static String userUrl = "https://oapi.dingtalk.com/user/listbypage";

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 通过调用接口获取access_token
     * @return String
     * 2022/03/08 09:30
     */
    public String getAccessToken() {
        String token = (String) redisUtils.get(CacheKey.DINGDING_TOKEN);
        if (ToolUtil.isEmpty(token)) {
            DingTalkClient client = new DefaultDingTalkClient(accessTokenUrl);
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(appKey);
            request.setAppsecret(appSecret);
            request.setHttpMethod("GET");
            OapiGettokenResponse response = null;
            try {
                response = client.execute(request);
            } catch (ApiException e) {
                e.printStackTrace();
            }
            token = response.getAccessToken();
            if (ToolUtil.isNotEmpty(token)) {
                redisUtils.set(CacheKey.DINGDING_TOKEN, token,7200);
            }
        }
        return token;
//        DingTalkClient client = new DefaultDingTalkClient(accessTokenUrl);
//        OapiGettokenRequest request = new OapiGettokenRequest();
//        request.setAppkey(appKey);
//        request.setAppsecret(appSecret);
//        request.setHttpMethod("GET");
//        OapiGettokenResponse response = null;
//        try {
//            response = client.execute(request);
//        } catch (ApiException e) {
//            e.printStackTrace();
//        }
//        return response.getAccessToken();
    }

    /**
     * 获取版天妖部门信息，
     * 529205900 固定为东更道总部的部门id
     * 1 固定为半天妖总部的部门id
     * @return OapiAttendanceListResponse
     * 2022-03-13
     */
    public OapiDepartmentListResponse getDepartmentList(){
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
        OapiDepartmentListRequest req = new OapiDepartmentListRequest();
        req.setFetchChild(true);
        req.setId("1");
        //req.setId("529205900");
        req.setHttpMethod("GET");
        String token = getAccessToken();
        OapiDepartmentListResponse rsp = null;
        try {
            rsp = client.execute(req, token);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return  rsp;

    }



    /**
     * 获取半天妖人员信息，
     * @return OapiAttendanceListResponse
     * 2022-04-14
     */
    public OapiUserSimplelistResponse getEmpList(Long deptid,Long offset,Long size){
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/listbypage");
        OapiUserSimplelistRequest req = new OapiUserSimplelistRequest();
        req.setDepartmentId(deptid);
        req.setOffset(offset);
        req.setSize(size);
        req.setHttpMethod("GET");
        String token = getAccessToken();
        OapiUserSimplelistResponse rsp = null;
        try {
            rsp = client.execute(req, token);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return  rsp;
    }



    /**
     * 获取半天妖人员信息，化简版，只传部门id
     * @return OapiAttendanceListResponse
     * 2022-04-14
     */
    public OapiUserSimplelistResponse getEmpSimpleList(Long deptid){
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/simplelist");
        OapiUserSimplelistRequest req = new OapiUserSimplelistRequest();
        req.setDepartmentId(deptid);
        req.setHttpMethod("GET");
        String token = getAccessToken();
        OapiUserSimplelistResponse rsp = null;
        try {
            rsp = client.execute(req, token);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return  rsp;
    }


    // 7100704,   工作时长
    // 7100705,   迟到次数
    // 7100706,   迟到时长
    // 7100710,   早退次数
    // 7100711,   早退时长
    // 7100724,   第一次打卡时间
    // 7100726,   第二次打卡时间
    // 7100728,   第三次打卡时间
    // 7100730,   第四次打卡时间
    // 7100732,   第五次打卡时间
    // 7100734,   第六次打卡时间
    // 7100736,   关联表单日期及详情
    // 7100701,   出勤班次
    // 7100715,   出差时长
    // 7100716,   外出时长
    // 7100723,   班次
    //private static final String COLS="7100704,7100705,7100706,7100710,7100711,7100724,7100726,7100728,7100730,7100732,7100734,7100736,7100701,7100715,7100716,7100723";






    // 7100704,   工作时长
    // 7100705,   迟到次数
    // 7100706,   迟到时长
    // 7100710,   早退次数
    // 7100711,   早退时长

    // 7100724,   第一次打卡时间
    // 7100725,   第一次打卡结果

    // 7100726,   第二次打卡时间
    // 7100727,   第二次打卡结果

    // 7100728,   第三次打卡时间
    // 7100729,   第三次打卡结果

    // 7100730,   第四次打卡时间
    // 7100731,   第四次打卡结果

    // 7100732,   第五次打卡时间
    // 7100733,   第五次打卡结果

    // 7100734,   第六次打卡时间
    // 7100735,   第六次打卡结果

    // 7100736,   关联表单日期及详情
    // 7100701,   出勤班次
    // 7100715,   出差时长
    // 7100716,   外出时长
    // 7100723,   班次

    //client-error:Invalid arguments:the array size of columnIdList must be less than 20.
    // 将第五次和第六次的备注先取消调
    private static final String COLS="7100704,7100705,7100706,7100710,7100711,7100724,7100725,7100726,7100727,7100728,7100729,7100730,7100731,7100732,7100734,7100736,7100701,7100715,7100716,7100723";


    /**
     * 获取半天妖人员考勤信息
     * 529205900 固定为东更道总部的部门id
     * @param userId
     * @param from
     * @param to
     * @return OapiAttendanceListResponse
     * 2022-03-13
     */

    public OapiAttendanceGetcolumnvalResponse getColumnvalList(String userId, String from, String to) {

        // 获取access_token
        String access_token = getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getcolumnval");
        OapiAttendanceGetcolumnvalRequest req = new OapiAttendanceGetcolumnvalRequest();
        req.setUserid(userId);
        req.setColumnIdList(COLS);
        req.setFromDate(StringUtils.parseDateTime(from +" 00:00:00"));
        req.setToDate(StringUtils.parseDateTime(to + " 23:59:59"));
        OapiAttendanceGetcolumnvalResponse response = null;
        try {
            response = client.execute(req, access_token);

        } catch (ApiException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 判断是否有打卡结果
     * @return OapiAttendanceListResponse
     * 2022/03/08 09:45
     */
    public OapiAttendanceListResponse getAttendanceList(String from, String to, String userId) {
        // 获取access_token
        String access_token = getAccessToken();
        // 通过调用接口获取考勤打卡结果
        DingTalkClient clientDingTalkClient = new DefaultDingTalkClient(attendanceUrl);
        OapiAttendanceListRequest requestAttendanceListRequest = new OapiAttendanceListRequest();
        // 查询考勤打卡记录的起始工作日
        requestAttendanceListRequest.setWorkDateFrom(from);
        // 查询考勤打卡记录的结束工作日
        requestAttendanceListRequest.setWorkDateTo(to);
        // 员工在企业内的userid列表，最多不能超过50个。
        requestAttendanceListRequest.setUserIdList(Arrays.asList(userId));
        // 表示获取考勤数据的起始点
        requestAttendanceListRequest.setOffset(0L);
        // 表示获取考勤数据的条数，最大不能超过50条。
        requestAttendanceListRequest.setLimit(50L);
        OapiAttendanceListResponse response = null;
        try {
            response = clientDingTalkClient.execute(requestAttendanceListRequest, access_token);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return response;
    }

    public Boolean deleteEmp(String userId) {
        // 获取access_token
        String access_token = getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/delete");
        OapiUserDeleteRequest req = new OapiUserDeleteRequest();
        req.setUserid(userId);
        Boolean ret = false;
        try  {
            OapiUserDeleteResponse rsp = client.execute(req, access_token);
            if (rsp.getErrcode() == 0) {
                ret = true;
            }
        }  catch (ApiException e) {
            e.printStackTrace();
        }
        return ret;
    }

    public HashMap<String, Object> deleteEmps(List<String> list) {
        List<String> result = new ArrayList<>();
        HashMap<String, Object> map = new HashMap<>();
        if (list.size() > 0) {
            for (String id : list) {
                if (!deleteEmp(id)) {
                    result.add(id);
                }
            }
        }
        if (result.size() > 0) {
            map.put("code", 1);
        } else {
            map.put("code", 0);
        }
        map.put("data", result);
        return map;
    }

    public OapiAttendanceGetcolumnvalResponse.ColumnValListForTopVo getColumnval(String userId, String from, String to) {
        // 获取access_token
        String access_token = getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getcolumnval");
        OapiAttendanceGetcolumnvalRequest req = new OapiAttendanceGetcolumnvalRequest();
        req.setUserid(userId);
        // 7100724 上班1打卡时间 7100726 下班1打卡时间 7100728 上班2打卡时间 7100730 下班2打卡时间 7100732 上班3打卡时间 7100734 下班3打卡时间7100736 关联的审批单
        req.setColumnIdList("7100724,7100726,7100728,7100730,7100732,7100734,7100736");
        req.setFromDate(StringUtils.parseDateTime(from));
        req.setToDate(StringUtils.parseDateTime(to));
        OapiAttendanceGetcolumnvalResponse response = null;
        OapiAttendanceGetcolumnvalResponse.ColumnValListForTopVo ret = null;
        try {
            response = client.execute(req, access_token);
            if (response.isSuccess()) {
                ret = response.getResult();
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return ret;
    }
    /**
     * 昨日某个员工打卡记录
     * @return List
     * 2022/03/08 11:00
     */
    public List getRecordByUserId(String userId) {
        String yestoday = DingdingUtil.getYestoday();
        String from = yestoday + " 00:00:00";
        String to = yestoday + " 23:59:59";
        List<OapiAttendanceListResponse.Recordresult> list = new ArrayList();
        OapiAttendanceListResponse attendanceListResponse = getAttendanceList(from, to, userId);
        if (attendanceListResponse.isSuccess() && attendanceListResponse.getRecordresult().size() > 0) {
            list = attendanceListResponse.getRecordresult();
        }
        return list;
    }

    /*时间函数*/
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        String result = format.format(today);
        return result;
    }

    /**
     * 昨日日期
     *
     * @return
     */

    public static String getYestoday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        String yesterday = new SimpleDateFormat( "yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }

    /**
     * 获取上午下午
     *
     * @param seconds
     * @return
     */
    public static String timestamp2A(Long seconds) {
        SimpleDateFormat sdf = new SimpleDateFormat("a");
        return sdf.format(new Date(seconds));
    }

    /**
     * 获取年
     *
     * @return
     */
    public static String getYear() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy");
        Date date = new Date();
        return format.format(date);
    }

    /**
     * 时间戳转换成时间格式字符串
     *
     * @param seconds
     * @return
     */
    public static String timestamp2Time(Long seconds) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.format(new Date(seconds));
    }

    /**
     * 时间戳转换成日期格式字符串
     *
     * @param strDate
     * @return
     */
    public static Date strToDate(String strDate) {
       SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
       ParsePosition pos = new ParsePosition(0);
       Date strtodate = formatter.parse(strDate, pos);
       return strtodate;
    }

    public static String dateToHms(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }



    /*时间函数*/
}
